<template>
  <span>
    <form-dialog
      :title="title"
      :visible="visible"
      @handleClose="handleClose"
    >
      <template #content>
        <el-form ref="form" :model="formData" :rules="formRule" label-width="170px" v-loading="loading">
          <el-form-item :label="$t('user.passwordRule.oldPw')" prop="old_password"  v-if="type !== 'desktop_user' && type !== 'system_admin'"
          >
            <el-input type="password" @keyup.enter.native="submit" v-model="formData.old_password" :placeholder="$t('user.passwordRule.oldPWempty')" show-password></el-input>
          </el-form-item>
          <el-form-item :label="$t('user.passwordRule.newPw')" prop="new_password" >
            <el-input type="password"  @keyup.enter.native="submit" v-model="formData.new_password" :placeholder="$t('user.passwordRule.newPWempty')" show-password ref="NewPassword">
              <el-button v-if="!(type === AuthModule.authrole && (item.username === AuthModule.username || item.name === AuthModule.username))" slot="append" icon="el-icon-refresh-right" @click="randomPasswordString"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('user.passwordRule.confirmNewPw')" prop="re_new_password">
            <el-input type="password" @keyup.enter.native="submit" v-model="formData.re_new_password" :placeholder="$t('user.passwordRule.newRePWEmpty')" show-password ref="ReNewPassword" />
          </el-form-item>
        </el-form>
        <span class="form-explain">{{ $t("user.passwordRule.complexityTip") }}</span>
      </template>
      <template #footer>
        <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="submit" :disabled="loading">{{ $t('common.confirm') }}</el-button>
      </template>
    </form-dialog>
  </span>
</template>
<script lang="ts">
import Vue from 'vue';
import ConfirmDialog from '../../../components/Dialog/confirmDialog.vue';
import FormDialog from '../../../components/Dialog/formDialog.vue';
import { AuthModule } from '../../../store/modules/auth';
import { randomPasswordString } from '../../../utils';

/**
 * 改自己的密码
 * * 需要输入原密码
 * * 密码默认密文显示
 * 
 * 改别人的密码
 * * 显示随机密码按钮
 * * 密码默认明文显示
 */
export default Vue.extend({
  components: { ConfirmDialog, FormDialog },
  computed: {
    title() {
      switch((this as any).type) {
        case 'desktop_user':
          return (this as any).$t('user.desktopUserResetPasswordTitle', (this as any).item.pretty_name ? (this as any).item : { pretty_name: (this as any).item.name });
        case 'system_admin':
          return (this as any).$t('user.systemManagerResetPasswordTitle', (this as any).item);
        case 'tenant_admin':
          return (this as any).$t('user.tenantManagerResetPasswordTitle', (this as any).item);
        default:
          return ""
      }
    },
    AuthModule: () => AuthModule,
    formRule() {
      const old_password = [
        { required: true, message: (this as any).$t('user.passwordRule.oldPWempty'), trigger: 'blur' },
        { max: 30, message: (this as any).$t("user.passwordRule.inputMax"), trigger: 'blur' },
        { validator: (rule: any, value: any, callback: any) => {
          (this as any).$systemTunnyApi.apiCheckPassword(value).then((res: any) => {
            if (res.check_password_flag) callback();
            else callback(new Error((this as any).$t("user.passwordRule.inputOldPWError")));
          }).catch((e: any) => {
            console.log(e);
            callback(e);
          });
        }, trigger: 'blur' }
      ];
      const new_password = [
        { required: true, message: (this as any).$t('user.passwordRule.newPWempty'), trigger: 'blur' },
        { max: 30, message: (this as any).$t("user.passwordRule.inputMax"), trigger: 'blur' },
        { validator: (rule: any, value: any, callback: any) => {
          if (/[' '|\u4e00-\u9fa5\s]/.test(value)) {
                callback(new Error((this as any).$t('common.noZh')));
              }
          else if (!/(?!.*\s)(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9]).{8,30}/.test(value)) {
            callback(new Error((this as any).$t("user.passwordRule.lowComplexity")));
          } else {
            callback();
          }
        }, trigger: 'blur' }
      ];

      const re_new_password = [
        { validator: (rule: any, value: any, callback: any) => {
          if (value != (this as any).formData.new_password) {
            callback(new Error((this as any).$t("user.passwordRule.passwordDifferent")));
          } else {
            callback();
          }
        }, trigger: 'blur' }
      ];

      if ((this as any).type === 'desktop_user' || (this as any).type === 'system_admin') {
        return {
          new_password,
          re_new_password
        }
      } else {
         return {
            old_password,
            new_password,
            re_new_password
          }
      }
    }
  },
  props: {
    resetMethod: {
      type: Function,
      default() {
        return () => Promise.resolve();
      }
    }
  },
  data() {
    return {
      visible: false,
      loading: false,
      type: '',
      item: null,
      uuid: '',
      formData: {
        old_password: "",
        new_password: "",
        re_new_password: ""
      }
    }
  },
  methods: {
    init(option: any) {
      (this as any).type = "";
      (this as any).uuid = "";
      (this as any).formData = {
        old_password: "",
        new_password: "",
        re_new_password: ""
      };
      (this as any).item = null;
      (this as any).item = option.item;
      (this as any).type = option.type;
      (this as any).uuid = option.item.uuid;
      (this as any).formData = {
        old_password: "",
        new_password: "",
        re_new_password: ""
      };

      (this as any).visible = true;

      (this as any).$nextTick(() => {
        // 这种情况下在修改自己的密码
        if (option.type === AuthModule.authrole && (option.item.username === AuthModule.username || option.item.name === AuthModule.username)) {
          (this as any).$refs['NewPassword'].passwordVisible = false;
          (this as any).$refs['ReNewPassword'].passwordVisible = false;
        } else {
          (this as any).$refs['NewPassword'].passwordVisible = true;
          (this as any).$refs['ReNewPassword'].passwordVisible = true;
        }
        (this as any).$refs.form.clearValidate();
      });
    },
    check() {
      return new Promise((resolve, reject) => {
        (this as any).$refs.form.validate((valid: any) => {
          if (valid) {
            resolve(valid);
          } else {
            reject()
          }
        });
      });
    },
    async submit() {
      await (this as any).check();
      (this as any).loading = true;
      (this as any).formData.new_password = (this as any).formData.new_password.normalize('NFKC');
      (this as any).formData.re_new_password = (this as any).formData.re_new_password.normalize('NFKC');
      (this as any).resetMethod((this as any).item, (this as any).formData).then(() => {
        (this as any).handleClose();
        (this as any).$message({
          message: this.$t('desktopManage.message.modifiedSuccessTips', { operation:  this.$t('navbar.ChangePassword')}),
          type: 'success'
        })
      }).catch(() => {
        (this as any).$message({
          message: this.$t('desktopManage.message.operationFail', { operation:  this.$t('navbar.ChangePassword')}),
          type: 'warning'
        })
      }).finally(() => {
        (this as any).loading = false;
      });
    },
    handleClose() {
      this.loading = false;
      (this as any).visible = false;
    },
    randomPasswordString() {
      const rp = randomPasswordString();
      (this as any).formData.new_password = rp;
      (this as any).formData.re_new_password = rp;
      (this.$refs['form'] as any).clearValidate();
    }
  }
})
</script>
<style lang="scss" scoped>
.form-explain {
  color: #BBBBBB;
  font-size: 12px;
  width: 100%;
  margin-bottom: 15px;
  display: block;
}
</style>
